<?php
namespace application\admin\controllers;

use mz\ars\Cases;
use Yii;
use mz\controllers\AdminController as Controller;

class CaseController extends Controller
{
    public $_type = 'case'; # 相册中数据类型

    #案例列表
    public function actionIndex()
    {
        $list = Cases::getAllCases([ 'isdel' => 0 ]);
        return $this->render('index',compact('list'));
    }

    # 添加 | 编辑 案例
    public function actionAdd()
    {
        $id = intval(Yii::$app->request->get('id',0));
        $case = empty($id) ? [] : Cases::find()->where(['id' => $id])->asArray()->one();
        return $this->render('add',compact('case'));
    }

    # 执行保存的操作
    public function actionSave()
    {
        if (!Yii::$app->request->isAjax) return $this->ajaxReturn(['e' => '2','m' => '请使用正确的请求方式']);

        $params = Yii::$app->request->post();
        $saveData = array_filter($params,function($key){
            return in_array($key , ['id','name','desc','isdel','content','url','category_id','completed']);
        },ARRAY_FILTER_USE_KEY);

        $saveData['completed'] = time();

        ## 基础信息保存
        $model = !empty($saveData['id']) ? Cases::findOne(['id' => $saveData['id']]) : new Cases();
        $model->attributes = $saveData;
        # 数据验证
        if (!$model->validate()){
            var_dump($model->getErrors());
            return $this->ajaxReturn(['e' => 1,'m' => "很遗憾，数据验证失败！"]);
        }

//todo 保存图片进入相册
//        $pictures = $params['picture'];
//        ## 相册信息保存
//        if ($pictures){
//            $albumData = [
//                'type' => $this->_type,
//                'type_id' => !empty($params['id']) ? $params['id'] : Yii::$app->db->getLastInsertID(),
//            ];
//
//            foreach ($pictures as $picture) {
//
//            }
//
//        }
//        $album =
//        # 执行保存
//        $trans = Yii::$app->db->beginTransaction();

        try{
            $msg = $model->save() ? ['e' => 0,'m' => "恭喜您，案例添加成功！"] : ['e' => '1','很遗憾，案例添加失败'];

        }catch (\Exception $e) {
            $msg = ['e' => 1 , 'm' => $e->getMessage()];
        }

        return $this->ajaxReturn($msg);
        
    }

    # 删除客户案例
    public function actionDelete()
    {
        $id = intval(Yii::$app->request->post('id',0));
        if(empty($id))return $this->ajaxReturn(['e' => 1 , 'm' => '必传参数id不能为空']);

        $caseObj = Cases::find()->where(['id' => $id])->one();
        $caseObj->attributes = ['id' => $id , 'isdel' => '1'];

        $msg = $caseObj->save() ? ['e' => 0 , 'm' => '恭喜您，删除成功！'] : ['e' => 1,'m' => '案例删除失败'];

        return $this->ajaxReturn($msg);
    }
}